/*
 * This file is part of GuitarMaster.
 * 
 * GuitarMaster is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GuitarMaster is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with GuitarMaster.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.paris5.master2.guitarmaster.dao;

/*
 * $Id: EcomDaoService.java 7 2013-03-13 08:38:30Z nedjahi.mourad@gmail.com $
 * 
 * $HeadURL: https://com-paris5-master2-guitarmaster-ejb.googlecode.com/svn/trunk/com.paris5.master2.guitarmaster-ejb/src/java/com/paris5/master2/guitarmaster/dao/EcomDaoService.java $
 * $Revision: 7 $
 * $Date: 2013-03-13 09:38:30 +0100 (mer., 13 mars 2013) $
 * $Author: nedjahi.mourad@gmail.com $
 */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Leticia Mahamed, Alice Khammy, mourad nedjahi, Saliou Mamadou Barry
 * 
 * Query builder 
 */
public enum EcomQuery {

    SEARCH_PRODUCT("SELECT p FROM Product p, ProductType pt, Score s WHERE p.idProductType=pt AND pt.score=s AND p.status=0 AND p.bidEndDate IS NULL AND UPPER(pt.title) LIKE UPPER(?1)", "s.score:pt.price:pt.title"),
    CATEGORY_PRODUCTS("SELECT p FROM Product p, ProductType pt, Category c, Score s WHERE p.idProductType=pt AND pt.idCategory=c AND pt.score=s AND pt.idCategory=?1 AND p.bidEndDate IS NULL", "s.score:pt.price"),
    CATEGORY_PRODUCT_TYPE("SELECT pt FROM ProductType pt, Category c, Score s WHERE pt.idCategory=c AND pt.score=s AND pt.idCategory=?1","s.score:pt.price"),
    CATEGORY_BY_TITLE("SELECT c FROM Category c WHERE c.title=?1","c.title"),
    PRODUCT_BIDS(
          "SELECT bid FROM Product p, ProductType pt, Bid bid "
        + "WHERE p.idProductType=pt "
        + "AND bid.idProduct=p " 
        + "AND p.idProduct=?1 "
        + "AND p.status=?2 "
        + "AND p.bidEndDate >= ?3"
        , "bid.dateCrea:bid.bidPrice"
    ),
    PRODUCT_BID_LAST_PRICE("SELECT b FROM Bid b WHERE b.idProduct = ?1","b.dateCrea"),
    PRODUCT_BID_LIST("SELECT p FROM Product p, ProductType pt WHERE p.idProductType=pt AND p.status=?1 AND p.bidEndDate >= ?2","pt.price:pt.idScore"),
    PRODUCTTYPE_COMMENTS("SELECT c FROM Comment c WHERE c.idProductType=?1","c.dateCreation"),
    SCORE_LAST_ID("SELECT max(s) FROM Score s", "s.idScore"),
    DISPONIBLE_PRODUCT("SELECT p FROM Product p, ProductType pt, Score s WHERE p.idProductType=pt AND p.ProductType=?1 AND p.status=0", "s.score:pt.price"),
    BILL_TO_PAY("SELECT b FROM Bill b WHERE b.datePay IS NULL AND b.idUser=?1","b.amount"),
    STORE_FIND("SELECT s FROM Store s WHERE s.name=?1","s.name:s.balance:s.code"),
    CODE_LIST("SELECT c.code FROM Country c","c.code"),
    SEACH_PRODUCT_BY_PRODUCT_TYPE("SELECT p FROM Product p, ProductType pt WHERE p.idProductType=pt AND pt.idProductType=?1 AND p.status=0","p.idProduct"),
    SEACH_SELLABLE_PRODUCT("SELECT p FROM ProductType p WHERE quantity>?1","p.title:p.price"),

    PRODUCT_TYPE_TITLE("SELECT pt FROM ProductType pt WHERE pt.title=?1","pt.price"),
    PRODUCT_PRICE_LESS_THAN("SELECT p FROM ProductType pt, Product p WHERE p.idProductType=pt AND pt.price<?1 AND p.status=0 AND p.bidEndDate IS NULL","pt.price"),
    PRODUCT_PRICE_BEWEN("SELECT pt FROM ProductType pt WHERE pt.price>?1 AND pt.price<?2","pt.price");
    
    private String query;
    private String order;
    private List<String> orderList;
    private boolean count;
    private int orderIndex;

    /**
     * Singleton construct
     * @param query
     * @param ord 
     */
    private EcomQuery(String query, String ord) {
        this.query = query;
        this.count=false;
        this.orderList = new ArrayList();
        orderList.addAll(Arrays.asList(ord.split(":")));
        this.setQueryOrder(0, false);
    }
    
    /**
     * build a select "count" query
     */
    public void setCountQuery(){
        this.count = true;
    }
    /**
     * build a select * query
     */
    public void setSelectQuery(){
        this.count = false;
    }
    
    /**
     * tells the query mode count/select
     * @return boolean 
     */
    public boolean isCountQuery(){
        return this.count;
    }
    
    /**
     * 
     * @param index
     * @param asc 
     */
    public void setQueryOrder(int index, boolean desc){
        this.orderIndex = (index>0 && index<=this.orderList.size())? index-1 : 0;
        this.order = " ORDER BY " + orderList.get(this.orderIndex)+ (desc? " DESC": " ASC");
    }
    
    /**
     * set the query order
     * @param desc boolean
     */
    public void setQueryOrder(boolean desc){
        
        if(this.order!=null){
            setQueryOrder(this.orderIndex,desc);
        }
        else{
            setQueryOrder(0,desc);
        }
    }
    
    /**
     * return the query string
     * @return String
     */
    public String getQuery() {
        if(this.count){
            String[] splited = query.split("FROM");
            String[] parts = query.split(" ");
            String toReplace=null;
            String prec = null;

            int i = 0;
            while(toReplace==null && i<parts.length){
                if(parts[i].equals("FROM")){
                    toReplace = prec;
                }

                prec = parts[i];
                i++;
            }

            if(toReplace!=null && splited.length==2){
                return splited[0].replace(toReplace, "COUNT("+toReplace+")")+"FROM" + splited[1];
            }
        }

        return this.query + this.order;
    }
}